package com.example.demo.controller;

import com.example.demo.pojo.Order;
import com.example.demo.service.OrderService;
import com.example.demo.util.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author BeauFang
 * Date: 2020/9/10
 */
@Slf4j
@Controller
public class SeckillingController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private SnowFlake snowFlake;

    @RequestMapping("/")
    public String index() {
        return "index";
    }


    @RequestMapping("/submitOrder")
    public String submitOrder(Model model) {
        if (!orderService.checkInventory()) {
            return "failed";
        }
        Order order = new Order();
        order.setId(String.valueOf(snowFlake.nextId()));
        // 测试固定写死
        order.setGoodsId("111111");
        order.setCreateTime(System.currentTimeMillis());
        order.setState(Order.STATE.UNPAY);
        orderService.submit(order);
        model.addAttribute("order", order);
        log.info("order id {}", order.getId());
        return "pay";
    }

    @RequestMapping("/pay")
    public String pay(@RequestParam("id") String orderId) {
        log.info("pay order  {} ", orderId);
        Order order = orderService.findById(orderId);
        if (order != null && order.getState() == Order.STATE.UNPAY) {
            order.setState(Order.STATE.FINISHED);
            orderService.save(order);
            return "success";
        } else {
            return "failed";
        }
    }

    @RequestMapping("failed")
    public String failed() {
        return "failed";
    }


    @RequestMapping("/initial")
    // 初始化库存
    @ResponseBody
    public String init() {
        orderService.initInventory();
        return "set initial inventory count 10";
    }
}
